package com.zjmzxfzhl.modules.app.service.impl;

import com.zjmzxfzhl.common.core.Result;
import com.zjmzxfzhl.common.core.constant.SysConstants;
import com.zjmzxfzhl.common.core.exception.SysException;
import com.zjmzxfzhl.common.core.util.CommonUtil;
import com.zjmzxfzhl.common.core.util.SecurityUtils;
import com.zjmzxfzhl.modules.app.entity.*;
import com.zjmzxfzhl.modules.app.form.AppDocVo;
import com.zjmzxfzhl.modules.app.form.AppModiVo;
import com.zjmzxfzhl.modules.app.form.DocFilePath;
import com.zjmzxfzhl.modules.app.service.*;
import com.zjmzxfzhl.modules.flowable.service.ProcessInstanceService;
import com.zjmzxfzhl.modules.flowable.vo.ProcessInstanceRequest;
import com.zjmzxfzhl.modules.sys.entity.SysUser;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zjmzxfzhl.common.core.base.BaseServiceImpl;
import com.zjmzxfzhl.modules.app.mapper.AppModiMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service
 * 
 * @author 张森荣
 */
@Service
public class AppModiServiceImpl extends BaseServiceImpl<AppModiMapper, AppModi>
        implements AppModiService {
    @Autowired
    private AppLogService appLogService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private AppProjService appProjService;
    @Autowired
    private AppDocService appDocService;
    @Autowired
    private AppTaskService appTaskService;

    @Override
    public IPage<AppModiVo> list(IPage<AppModiVo> page, AppModiVo appModiVo) {
        return page.setRecords(baseMapper.list(page, appModiVo));
    }

    @Override
    public List<AppModiVo> getList(AppModiVo appModiVo) {
        return baseMapper.list(null, appModiVo);
    }
    /**
     * 待审批
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pendingTrial(String modiId) {
        AppModi appModi=this.getById(modiId);
        if(appModi==null){
            return false;
        }
        appModi.setStatus("00");
        appModi.setUpdateTime(new Date());
        Boolean result = this.updateById(appModi);

        appLogService.addLog("变更状态更改为 待审批","06",appModi.getModiId());
        return result;
    }
    /**
     * 审批中
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean inReview(String modiId) {
        AppModi appModi=this.getById(modiId);
        if(appModi==null){
            return false;
        }
        appModi.setStatus("01");
        appModi.setUpdateTime(new Date());
        Boolean result = this.updateById(appModi);

        appLogService.addLog("变更状态更改为 审批中","06",appModi.getModiId());
        return result;
    }
    /**
     * 审批过
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reviewed(String modiId) {
        AppModi appModi=this.getById(modiId);
        if(appModi==null){
            return false;
        }
        appModi.setStatus("02");
        appModi.setUpdateTime(new Date());
        Boolean result = this.updateById(appModi);

        appLogService.addLog("变更状态更改为 审批过","06",appModi.getModiId());
        return result;
    }
    /**
     * 已驳回
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reject(String modiId) {
        AppModi appModi=this.getById(modiId);
        if(appModi==null){
            return false;
        }
        appModi.setStatus("03");
        appModi.setUpdateTime(new Date());
        Boolean result = this.updateById(appModi);

        appLogService.addLog("变更状态更改为 已驳回","06",appModi.getModiId());
        return result;
    }
    /**
     * 已关闭
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean close(String modiId) {
        AppModi appModi=this.getById(modiId);
        if(appModi==null){
            return false;
        }
        appModi.setStatus("04");
        appModi.setUpdateTime(new Date());
        Boolean result = this.updateById(appModi);

        appLogService.addLog("变更状态更改为 已关闭","06",appModi.getModiId());
        return result;
    }
    /**
     * 新增变更记录
     *
     * @param appModi
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppModi launchChange(AppModi appModi) {
        //添加项目
        Boolean result = this.saveAppModi(appModi);
        if(result==false){
            return null;
        }
        appModi=this.getById(appModi.getModiId());
        switch (appModi.getModiType()) {
            case "00": //项目变更
                switch (appModi.getModiSubtype()) {
                    case "00": //普通变更
                    case "01": //中止变更
                    case "02": //重启变更
                    case "03": //终止变更
                        AppProj appProj = appProjService.getById(appModi.getModiTypeId());
                        appProj.setIsModi("1");
                        appProj.setUpdateTime(new Date());
                        appProjService.updateById(appProj);
                        appModi.setOldStartDate(appProj.getStartDate());
                        appModi.setOldEndDate(appProj.getEndDate());
                        this.updateById(appModi);
                        appModi=this.getById(appModi.getModiId());
                        break;
                }
                break;
            case "01": //任务变更

                break;
            case "02": //产品变更

                break;
            case "03": //文档变更

                break;
            case "04": //合同变更

                break;
        }
        //发起变更流程
        processStart(appModi.getModiId());

        return appModi;
    }

    /**
     * 启动变更审批流程实例
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processStart(String modiId) {

        AppModi appModi=this.getById(modiId);
        if(appModi==null){
            return false;
        }
        if(appModi.getModelId()==null){
            throw new FlowableException("发起流程失败！检查是否存在流程！");
        }
        if("01".equals(appModi.getStatus())||"02".equals(appModi.getStatus())){
            throw new FlowableException("已发起过流程！");
        }
        ProcessInstanceRequest processInstanceRequest=new ProcessInstanceRequest();
        processInstanceRequest.setProcessDefinitionId(appModi.getModelId());
        processInstanceRequest.setBusinessKey("modi:"+appModi.getModiId());
        ProcessInstance instance = processInstanceService.start(processInstanceRequest);
        appModi.setProcessInstanceId(instance.getProcessInstanceId());
        appModi.setUpdateTime(new Date());
        this.updateById(appModi);

        Boolean result=inReview(modiId);

        //添加变更日志
        switch (appModi.getModiType()) {
            case "00": //项目变更
                switch (appModi.getModiSubtype()) {
                    case "00": //普通变更
                        appLogService.addLog("发起项目普通变更审批","06",modiId);
                        break;
                    case "01": //中止变更
                        appLogService.addLog("发起项目中止变更审批","06",modiId);
                        break;
                    case "02": //重启变更
                        appLogService.addLog("发起项目重启变更审批","06",modiId);
                        break;
                    case "03": //终止变更
                        appLogService.addLog("发起项目终止变更审批","06",modiId);
                        break;
                }
                break;
            case "01": //任务变更
                break;
            case "02": //产品变更
                break;
            case "03": //文档变更
                break;
            case "04": //合同变更
                break;
        }
        return result;
    }
    /**
     * 查询项目是否需要发起变更
     *
     * @return
     */
    @Override
    public boolean projChange(String projId,String modiSubtype) {
        AppProj appProj=appProjService.getById(projId);
        if(appProj==null){
            return false;
        }
        if("1".equals(appProj.getIsModi())){
            return false;
        }
        switch (modiSubtype) {//不允许变更条件
            case "00": //普通变更
                if (!"0".equals(appProj.getRevise())) {
                    return false;
                }
                break;
            case "01": //中止变更
                if (!"01".equals(appProj.getStatus())) {
                    return false;
                }
                break;
            case "02": //重启变更
                if (!"04".equals(appProj.getStatus())) {
                    return false;
                }
                break;
            case "03": //终止变更
                if ("02".equals(appProj.getStatus())||"03".equals(appProj.getStatus())) {
                    return false;
                }
                break;
            default:
                return false;
        }
        return true;
    }

    /**
     * 查询审核文档
     *
     * @param processInstanceId
     * @return
     */
    public List<AppModiVo> procModi(String processInstanceId) {
        return baseMapper.procModi(processInstanceId);
    }

    /**
     * 新增项目，自动计算机构级别、机构级次码、是否叶子
     *
     * @param appModi
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAppModi(AppModi appModi){
        List<DocFilePath> docFilePaths= null;
        if(appModi.getDocFilePath()!=null){
            docFilePaths=appModi.getDocFilePath();
        }
        //添加项目
        Boolean result = this.save(appModi);
        if(result==false){
            return false;
        }
        appModi=this.getById(appModi.getModiId());
        //添加变更附件
        if (docFilePaths != null && docFilePaths.size() > 0) {
            AppDoc appDoc=new AppDoc();
            appDoc.setDocFilePath(docFilePaths);
            appDoc.setDeleted("0");
            appDoc.setName("变更附件");
            appDoc.setDirId("##");
            appDoc.setDocType("08");
            appDoc.setDocTypeId(appModi.getModiId());
            appDoc.setContent("发起变更附带文件");
            appDocService.saveAppDoc(appDoc);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delByIds(String ids) {
        Boolean result = true;
        String[] idsArr = ids.split(",");

        for (String s:idsArr) {
            AppModi appModi=this.getById(s);
            if ("01".equals(appModi.getModiType())) {
                AppTask task = appTaskService.queryById(appModi.getModiTypeId());
                if(task==null){
                    throw new FlowableException("任务不存在!");
                }
//                if (task.getProjId() != null) {
//                    AppProj appProj = appProjService.queryById(task.getProjId());
//                    String userId = SecurityUtils.getUserId();
//                    if (!userId.equals(appProj.getMasterUserId())) {
//                        throw new FlowableException("不是项目负责人无法删除变更记录!");
//                    }
//                }
            }
            //删除产品
            result= this.removeById(s);
        }
        return result;
    }
}
